# -*- coding: utf-8 -*-
"""
@Time   : 2019/11/21 15:12
@Author : LeeCQ
"""
import os
import re
import asyncio
import requests
from HTTP.Downloader1024.common.functions import getHtml

album = './photos/'
header = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}


async def get_photos(photo_list, album_name):
    """

    :param photo_list:
    :param album_name:
    :return:
    """
    def get_a_photo(photo_url):
        local_photo_path = f'{album}/{album_name}/{photo_url[-12:]}'
        if os.path.exists(local_photo_path):
            return 1, local_photo_path
        try:
            open(local_photo_path, 'wb').write(requests.get(photo_url, headers=header).content)
            return 0, local_photo_path
        except:
            return -1, local_photo_path

    for _p in photo_list:
        yield get_a_photo(_p)


async def get_album(album_url):
    """
    获取相册的全部内容； name - photos
    :param album_url:
    :return:
    """

    head, page = getHtml(album_url, headers=header)
    # album_name = re.findall(r'<title>(.*?)</title>', page)[0]
    # album_name = album_name[:album_name.find('|')]
    album_name = re.findall(r'<span id="subject_tpc">(.*?)</span>', page)[0]
    listURL = re.findall(r'<img src="(.*?)" border="0"', page)
    print(album_name, listURL)
    return_code, photo = await get_photos(listURL, album_name)  # 创建迭代器
    #




def main(_url):
    loop = asyncio.get_event_loop()
    tasks = asyncio.ensure_future(get_album(_url))
    loop.run_until_complete(asyncio.wait(tasks))
    print("all task is finish")
    loop.close()
    # get_album(_url)


if __name__ == '__main__':
    url = 'http://q1.fnmdsbb.xyz/pw/html_data/114/1911/4441681.html'
    main(url)
